package com.besttone.search.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.besttone.search.model.PhoneInfo;

public class PhoneUtil {
	private static final String TAG = "PhoneUtil";
	public PhoneInfo getPhoneNoByIMSI(String imsi) throws Exception {
		PhoneInfo info;
		
		// 生成请求xml
		String reqXml = createParm(imsi);

		//返回XML
		String rtnXml = getRtnXml(reqXml);
		
		//DOM方式解析XML
		info = dealXml(rtnXml);
		
		return info;
	}

	public PhoneInfo dealXml(String rtnXml) {
		PhoneInfo info = new PhoneInfo();
		try {
			// 创建解析工厂
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			// 指定DocumentBuilder
			DocumentBuilder builder = factory.newDocumentBuilder();
			// 从文件构造一个Document，因为XML文件中已经指定了编码，所以这里不必了
			ByteArrayInputStream is = new ByteArrayInputStream(rtnXml.getBytes("UTF-8"));
			Document document = builder.parse(is);

			//得到Document的根
			Element root = document.getDocumentElement();
			NodeList nodes = root.getElementsByTagName("data");
			
			// 遍历根节点所有子节点
			for (int i = 0; i < nodes.getLength(); i++) {
				// 获取data元素节点
				Element phoneElement = (Element) (nodes.item(i));
				// 获取data中mobile属性值
				info.setPhoneNo(phoneElement.getAttribute("mobile"));
			}
			
			NodeList list = root.getElementsByTagName("error");
			// 遍历根节点所有子节点
			for (int i = 0; i < list.getLength(); i++) {
				info.setErrorFlag(true);
				Element errElement = (Element) (list.item(i));
				// 获取errorCode属性
				NodeList codeNode = errElement.getElementsByTagName("errorCode");
				// 获取errorCode元素
				Element codeElement = (Element)codeNode.item(0);
				//获得errorCode元素的第一个值
				String errorCode = codeElement.getFirstChild().getNodeValue();
				info.setErrorCode(errorCode);
				
				// 获取errorMsg属性
				NodeList msgNode = errElement.getElementsByTagName("errorMessage");
				// 获取errorMsg元素
				Element msgElement = (Element)msgNode.item(0);
				//获得errorMsg元素的第一个值
				String errorMsg = msgElement.getFirstChild().getNodeValue();
				info.setErrorMsg(errorMsg);
			}
			
		} catch (Exception e) {
			Log.e(TAG, "XML解析出错；"+e.getMessage());
		}
		
		return info;
	}

	public String getRtnXml(String reqXml) throws UnsupportedEncodingException,
			IOException, ClientProtocolException {
		//返回XML
		String rtnXml = "";
		
		//http地址
		StringBuilder requestUrl = new StringBuilder(Constants.serverAddress);
		String parm = "?reqXml=" + URLEncoder.encode(reqXml, "UTF-8") + "&sign=" + MD5Builder.getMD5Str(reqXml + Constants.appSecret);
		requestUrl.append(parm);
		String httpUrl = requestUrl.toString();
		//HttpGet连接对象
		HttpGet httpRequest = new HttpGet(httpUrl);  
		//取得HttpClient对象  
		HttpClient httpclient = new DefaultHttpClient(); 
		//请求HttpClient，取得HttpResponse  
			HttpResponse httpResponse = httpclient.execute(httpRequest); 
			//请求成功  
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//取得返回的字符串  
				rtnXml = EntityUtils.toString(httpResponse.getEntity()).trim(); 
			}
			return rtnXml;
	}

	public String createParm(String imsi) {
		StringBuffer parmXml = new StringBuffer("");
		parmXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		parmXml.append("<reqXML version=\"1.0\">");
		String appKeyParm = "<appKey>" + Constants.appKey + "</appKey>";
		String apiNameParm = "<apiName>" + Constants.apiName + "</apiName>";
		String apiMethodParm = "<apiMethod>" + Constants.apiMethod + "</apiMethod>";
		String timestampParm = "<timestamp>" + getTimeStamp() + "</timestamp>";
		parmXml.append(appKeyParm);
		parmXml.append(apiNameParm);
		parmXml.append(apiMethodParm);
		parmXml.append(timestampParm);
		parmXml.append("<params>");
		String mobileParm = "<param name=\"imsi\" value=\"" + imsi + "\"/>";
		parmXml.append(mobileParm);
		parmXml.append("</params>");
		parmXml.append("</reqXML>");
		String parmXmlStr = parmXml.toString();
		return parmXmlStr;
	}
	
    public String getTimeStamp() {
    	String timestamp = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		timestamp = sdf.format(new Date());
		return timestamp;
    }
    
}
